/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2022-10-16 17:18:01
 * @LastEditors: Clark
 * @LastEditTime: 2022-11-15 10:51:41
 * @Description: file content
 */

#include "daytime.h"
#include "muduo/base/Logging.h"
#include "muduo/net/EventLoop.h"

DaytimeServer::DaytimeServer(EventLoop* loop, const InetAddress& listenAddr)
  : tcpServer(loop, listenAddr, "DaytimeServer")
{
  tcpServer.setConnectionCallback(std::bind(&DaytimeServer::onConnection, this, _1));
  tcpServer.setMessageCallback(std::bind(&DaytimeServer::onMessage, this, _1, _2, _3));
}

void DaytimeServer::start()
{
  tcpServer.start();
}

void DaytimeServer::onConnection(const TcpConnectionPtr& conn)
{
  LOG_INFO << "DaytimeServer - " << conn->peerAddress().toIpPort() << " -> "
           << conn->localAddress().toIpPort() << " is "
           << (conn->connected() ? "UP" : "DOWN");

  if (conn->connected())
  {
    conn->send(Timestamp::now().toFormattedString() + "\n");
    conn->shutdown();
  }
}

void DaytimeServer::onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time)
{
  string msg(buf->retrieveAllAsString());
  LOG_INFO << conn->name() << " discards " << msg.size()
           << " bytes received at " << time.toString();
}
